(function(){
	var AjaxCrud = QualityCheck.AjaxCRUD;
	var serverUrl = QualityCheck.GPUD.ServiceConfig;
	var currentPage = 1;
	var pageSize = 10;
	var totalSize;
	var now = 0;
	var dataCache = [];
	var currentPageMore = 1;
	var pageSizeMore = 4;
	$(function(){
		var usercode = $("#user-name",parent.parent.document).attr("code");
		var userkey = $("#user-name",parent.parent.document).attr("key");
		var usertype = $("#user-name",parent.parent.document).attr("usertype");
		keyCheck(usercode,usertype,userkey,function(){
			initSmPages();
			window.onresize = function () {
				initSmPages();
			};
			pagebtns();
			initRole(currentPage,pageSize);
		});
	});
	function initRole(currentpage,pagesize){
		var userKey = $("#user-name",parent.parent.document).attr("key");	
		var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
		var name = encodeURI($("#role-name").val());
		var data = {
				cmd:"getRole",
				model:"license",
				userKey:userKey,
				data:{
					currentpage:currentpage,
					pagesize:pagesize,
					schoolcode:schoolcode,
					name:name,
				},
				remark:"",
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			var content = "";
			var pagecontent = "<div class=\"pages-btn-next\">&gt;&gt;</div>";
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var data = res.data.data;
				var total = res.data.total;
				totalSize = Math.ceil(total/pagesize);
				if(totalSize <= 5 && totalSize >0){
					for(var i = totalSize-1 ; i >= 0; i--){
						if(i == currentpage-1){
							pagecontent += "<div class=\"pages-btn page-btn-select\">"+(i + 1)+"</div>"; 
						}else{
							pagecontent += "<div class=\"pages-btn\">"+(i + 1)+"</div>"; 
						}
					}
				}else if(totalSize == 0){
					pagecontent += "<div class=\"pages-btn\">1</div>";
				}else if(totalSize > 5){
					var lastp = (now*5)+5;
					if(lastp > totalSize){
						lastp = totalSize;
					}
					for(var i = lastp-1 ; i >= (now*5); i--){
						if(i == currentpage-1){
							pagecontent += "<div class=\"pages-btn page-btn-select\">"+(i + 1)+"</div>"; 
						}else{
							pagecontent += "<div class=\"pages-btn\">"+(i + 1)+"</div>"; 
						}
					}
				}
				pagecontent += "<div class=\"pages-btn-last\">&lt;&lt;</div>";
				$("#role-page").empty();
				$("#role-page").append(pagecontent);
				
				$(".pages-btn").unbind("click");
				$(".pages-btn").click(function(){
					dataCache = [];
					$(".pages-btn").removeClass("page-btn-select");
					$(this).addClass("page-btn-select");
					currentPage = parseInt($(this).text());
					initRole(currentPage,pageSize);
				});
				
				$(".pages-btn-last").unbind("click");
				$(".pages-btn-last").click(function(){
					if(totalSize <= 5 && totalSize >0){
						return false;
					}else if(totalSize == 0){
						return false;
					}else if(totalSize > 5){
						if(now > 0){
							now --;
							initRole((now*5+1),pageSize);
						}else{
							return false;
						}
					}
				});
				
				$(".pages-btn-next").unbind("click");
				$(".pages-btn-next").click(function(){
					if(totalSize <= 5 && totalSize >0){
						return false;
					}else if(totalSize == 0){
						return false;
					}else if(totalSize > 5){
						if(totalSize%5 == 0){
							if((now+1) < totalSize/5){
								now ++;
								initRole((now*5+1),pageSize);
							}else{
								return false;
							}
						}else{
							if((now+1) <= (totalSize-totalSize%5)/5){
								now ++;
								initRole((now*5+1),pageSize);
							}else{
								return false;
							}
						}
					}
				});
				if(data.length > 0){
					for(var i = 0; i < data.length; i++){
						for(var key in data[i]){
							if(data[i][key] == null || data[i][key] == "null" ){
								data[i][key] = "";
							}
						}
						content += "<div class=\"table-trs\">" +
							"<div class=\"tables-headimg\">" +
//								"<img src=\"../../../../../../"+ServiceName+data[i].headimg+"\" width=\"100%\" height=\"100%\"/>" +
							"</div>" +
							"<div class=\"tables-left\">" +
								"<div class=\"table-name\" title='"+data[i].name+"' style='width:400px;text-align:left;'>"+substr(data[i].name,8)+"</div>" +
								"<div class=\"table-code\" title='"+data[i].describe+"'style='width:400px;text-align:left;'>"+substr(data[i].describe,25)+"</div>" +
							"</div>" +
//							"<div class=\"tables-middle\">" +
//								"<div class=\"table-class\" title=\"手机号\">"+isUndefined(data[i].cellphone)+"</div>" +
//								"<div class=\"table-code\">"+isUndefined(data[i].email)+"</div>" +
//							"</div>" +
							"<div class=\"tables-right\">" +
								"<div class=\"table-address\">所属学校： "+data[i].schoolname +"</div>" +
								"<div class=\"table-oprate\">" +
									"<div class=\"table-detail\" dataindex = \""+i+"\" usercode=\""+data[i].id+"\" title=\"详情\"></div>" +
									"<div class=\"table-edit\" dataindex = \""+i+"\" usercode=\""+data[i].id+"\" title=\"编辑\"></div>" +
									"<div class=\"table-delete\" dataindex = \""+i+"\" usercode=\""+data[i].id+"\" title=\"删除\"></div>" +
									"<div class=\"table-user\" dataindex = \""+i+"\" usercode=\""+data[i].code+"\" title=\"用户\"></div>" +
								"</div>" +
							"</div>" +
						"</div>";
						dataCache.push(data[i]);
					}
					$("#role-data-show").empty();
					$("#role-data-show").append(content);
					
					$(".table-trs").unbind("hover");
					$(".table-trs").hover(function(){
						$(this).find(".table-oprate").show();
					},function(){
						$(".table-oprate").hide();
					});
					
					$(".table-detail").unbind("click");
					$(".table-detail").click(function(){
						$("#role-detailform").show();
						$("#right-role-tables").hide();
						var index = parseInt($(this).attr("dataindex"));
						$("#role-detailform").contents().find("input").attr("readonly","readonly");
						$("#role-detailform").contents().find("input").css("background-color","#E5E5E5");
						$("#role-detailform").contents().find(".news-div div").attr("contenteditable","false");
						$("#role-detailform").contents().find(".news-div div").css("background-color","#E5E5E5");
						$("#role-detailform").contents().find("#save-btns-content").hide();
						$("#role-detailform").contents().find("#back-to-table").unbind("click");
						$("#role-detailform").contents().find("#back-to-table").click(function(){
							$("#role-detailform").hide();
							$("#right-role-tables").show();
							dataCache = [];
							initRole(currentPage,pageSize);
						});
						showData(dataCache[index]);
					});
					
					$(".table-edit").unbind("click");
					$(".table-edit").click(function(){
						$("#role-detailform").show();
						$("#right-role-tables").hide();
						var index = parseInt($(this).attr("dataindex"));
						var id = $(this).attr("usercode");
						$("#role-detailform").contents().find("input").removeAttr("readonly","readonly");
						$("#role-detailform").contents().find("input").css("background-color","#FFF");
						$("#role-detailform").contents().find(".news-div div").attr("contenteditable","true");
						$("#role-detailform").contents().find(".news-div div").css("background-color","#FFF");
						$("#role-detailform").contents().find("#save-btns-content").show();
						$("#role-detailform").contents().find("#back-to-table").unbind("click");
						$("#role-detailform").contents().find("#back-to-table").click(function(){
							$("#role-detailform").hide();
							$("#right-role-tables").show();
							dataCache = [];
							initRole(currentPage,pageSize);
						});
						showData(dataCache[index]);
						$("#role-detailform").contents().find("#role-add").unbind("click");
						$("#role-detailform").contents().find("#role-add").click(function(){
							if(checkUser() && check2("check-fail","role-detailform")){
								updateRole(id);
							}
						});
						check1("role-name",isNull,"null","role-detailform");
						
					});
					$(".table-delete").unbind("click");
					$(".table-delete").click(function(){
						var id = $(this).attr("usercode");
						deleteBox("确定要删除吗？",function(){
							deleteRole(id);
						});
					});
					$(".table-user").unbind("click");
					$(".table-user").click(function(){
						$(".title-search").hide();
						$(".right-content").hide();
						$("#right-role-tables").hide();
						$("#user-search").show();
						$("#user-detailform").show();
						var code = $(this).attr("usercode");
						initUser(currentPage,pageSizeMore,code);
						
						$("#user-detailform").contents().find("#back-to-table").unbind("click");
						$("#user-detailform").contents().find("#back-to-table").click(function(){
							$(".title-search").hide();
							$(".right-content").hide();
							$("#role-search").show();
							$("#right-role-tables").show();
							dataCache = [];
							currentPageMore = 1;
							$("#user-detailform").contents().find("#user-data-show").empty();
							$("#user-detailform").contents().find(".save-btns").hide();
							initRole(currentPage,pageSize);
						});
						$("#user-detailform").contents().find("#add-role-user").unbind("click");
						$("#user-detailform").contents().find("#add-role-user").click(function(){
							showRoleDialog(code);
						});

						
					});
				}else{
					content += "<div class=\"table-trs\">" +
									"<div class=\"no-data-show\">没有查到相关结果！</div>" +
								"</div>";
					$("#role-data-show").empty();
					$("#role-data-show").append(content);
				}
			}else{
				content += "<div class=\"table-trs\">" +
								"<div class=\"no-data-show\">没有查到相关结果！</div>" +
							"</div>";
				$("#role-data-show").empty();
				$("#role-data-show").append(content);
			}
		},null,null);	
	}
	function showRoleDialog(code){
		var contents = "<div class='title-search index-dialog-content-search'>" +
				"<a class='select-btn' id='selectAll'>全选</a>" +
				"<a class='select-btn' id='unselect'>反选</a>" +
				"<a class='select-btn' id='selectNone'>全不选</a></div>" +
				"<div class='index-dialog-data'>" +
				"<div class='index-dialog-data-title'></div>" +
				"<div class='index-dialog-data-cont'></div>" +
				"</div>";
		var obj = {
				width:500,
				height:400,
				title:"新增用户",
				contents:contents
			  };
		userChoice(obj,function(){
			getAllUser();
		});
		$("#selectAll",parent.parent.document).unbind("click");
		$("#selectAll",parent.parent.document).bind("click",function(){
			$("[name = 'select-user']:checkbox",parent.parent.document).prop("checked",true);
		});
		$("#selectNone",parent.parent.document).unbind("click");
		$("#selectNone",parent.parent.document).bind("click",function(){
			$("[name = 'select-user']:checkbox",parent.parent.document).removeAttr("checked");
		});
		$("#unselect",parent.parent.document).unbind("click");
		$("#unselect",parent.parent.document).bind("click",function(){
			$("[name = 'select-user']:checkbox",parent.parent.document).each(function(){
				var checked = $(this,parent.parent.document).prop("checked");
				if(checked == true){
					$(this,parent.parent.document).removeAttr("checked");
				}else if(checked == false){
					$(this,parent.parent.document).prop('checked',true);
				};
			});
		});
		$("#sure-btn",parent.parent.document).unbind("click");
		$("#sure-btn",parent.parent.document).bind("click",function(){
			roleBindUsers(code);
			$(".index-dialog",parent.parent.document).hide();
			$(".index-dialog-cover",parent.parent.document).hide();
		});
		$("#cancel-btn",parent.parent.document).unbind("click");
		$("#cancel-btn",parent.parent.document).bind("click",function(){
			$(".index-dialog",parent.parent.document).hide();
			$(".index-dialog-cover",parent.parent.document).hide();
		});
		
	}
	function roleBindUsers(code){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var paramsArr = [];
		$("[name = 'select-user']:checkbox",parent.parent.document).each(function(){
			var checked = $(this,parent.parent.document).prop("checked");
			if(checked == true){
				var params = {};
				params["usercode"] = $(this,parent.parent.document).val();
				params["usertype"] = 0;
				params["code"] = code;
				paramsArr.push(params);
			};
		});
		var data = {
				cmd:"insertRoleUser",
				model:"license",
				userKey:userKey,
				data:JSON.stringify(paramsArr),
				remark:"",						
		};
		processBegin("正在运行中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("新增用户成功");
				$("#user-detailform").contents().find("#user-data-show").empty();
				initUser(currentPage,pageSizeMore,code);			
			}else{
				processError("新增用户失败");
			}
		},null,null);
	}
	function getAllUser(){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
		var userType = 0;
		var data = {
				cmd:"getAllUserWithStudent",
				model:"user",
				userKey:userKey,
				data:{
					usertype:userType,
					schoolcode:schoolcode,
				},
				remark:"",						
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			var content = "<table class='index-dialog-data-info'>";
			var contentTitle = "<table class='index-dialog-data-info'><tr style='height:34px;'><td>选择</td><td>用户别名</td><td>用户名</td><td>用户状态</td><td>角色名称</td></tr></table>";
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var data = res.data.data;
				if(data.length > 0){					
					for(var i = 0; i < data.length; i++){
						if(data[i].islock == true || data[i].islock == "true"){
							data[i].islock = "正常";
						}else if(data[i].islock == false || data[i].islock == "false"){
							data[i].islock = "锁定";
						}
						if(data[i].name == null || data[i].name == "null"){
							data[i].name = "--";
						}
						content += "<tr><td><input type='checkbox' name='select-user' value='"+data[i].usercode+"'></td><td>"+data[i].alias+"</td><td>"+data[i].usercode+"</td><td>"+data[i].islock+"</td><td>"+data[i].name+"</td></tr>";
					}
				}else{
					content += "<tr><td colspan = '5'>没有相关信息！</td></tr>";
				}
				content += "</table>";
					
			}else{
				content += "<tr><td colspan = '5'>查询用户失败！</td></tr></table>";
			}
			
			$(".index-dialog-data-title",parent.parent.document).html(contentTitle);
			$(".index-dialog-data-cont",parent.parent.document).html(content);
		},null,null);	
	}
	function showData(data){
		for(key in data){
			if($("#role-detailform").contents().find("#role-" + key).length != 0){
				if($("#role-detailform").contents().find("#role-" + key)[0].tagName.toLowerCase() == "input"){
					$("#role-detailform").contents().find("#role-" + key).val(data[key]);
				}else{
					$("#role-detailform").contents().find("#role-" + key).html(data[key]);
				}
			}
		}
	}
	function initUser(currentpage,pagesize,code){
		var userKey = $("#user-name",parent.parent.document).attr("key");	
		var name = encodeURI($("#user-name").val());
		var data = {
				cmd:"getRoleUser",
				model:"license",
				userKey:userKey,
				data:{
					currentpage:currentpage,
					pagesize:pagesize,
					name:name,
					code:code,
				},
				remark:"",
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			var content = "";
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var data = res.data.data;
				var total = res.data.total;
				totalSize = Math.ceil(total/pagesize);
				if(data.length > 0){
					for(var i = 0; i < data.length; i++){
						for(var key in data[i]){
							if(data[i][key] == null || data[i][key] == "null" ){
								data[i][key] = "";
							}
						}
						content += "<div class=\"table-trs\">" +
							"<div class=\"tables-headimg\">" +
//								"<img src=\"../../../../../../"+ServiceName+data[i].headimg+"\" width=\"100%\" height=\"100%\"/>" +
							"</div>" +
							"<div class=\"tables-left\">" +
								"<div class=\"table-name\" title=\""+data[i].alias+"\"\>"+substr(data[i].alias,6)+"</div>" +
								"<div class=\"table-code\">"+data[i].cellphone+"</div>" +
							"</div>" +
							"<div class=\"tables-middle\">" +
								"<div class=\"table-class\">"+isUndefined(data[i].imei)+"</div>" +
								"<div class=\"table-code\" title=\""+data[i].address+"\">"+substr(data[i].address,8)+"</div>" +
							"</div>" +
							"<div class=\"tables-right\">" +
								"<div class=\"table-address\" ></div>" +
								"<div class=\"table-oprate\">" +
									"<div class=\"table-delete\" dataindex = \""+i+"\" userkey=\""+data[i].userkey+"\" title=\"删除\"></div>" +
								"</div>" +
							"</div>" +
						"</div>";
						dataCache.push(data[i]);
					}
					$("#user-detailform").contents().find("#user-data-show").append(content);
					$("#user-detailform").contents().find(".save-btns").show().text("加载更多。。。");
					
					if(total <= pagesize && total >= 0){
						$("#user-detailform").contents().find(".save-btns").hide();
					}else if(total > pagesize){
						if(currentpage < totalSize){
							$("#user-detailform").contents().find(".save-btns").show().text("加载更多。。。");
						}else{
							$("#user-detailform").contents().find(".save-btns").hide();
						}
						$("#user-detailform").contents().find(".save-btns").unbind("click");
						$("#user-detailform").contents().find(".save-btns").click(function(){
							currentpage ++;
							currentPageMore = currentpage;
							if(currentpage <= totalSize){
								initUser(currentpage,pagesize,code);
							}
						});
						
					}
					$("#user-detailform").contents().find(".table-trs").unbind("hover");
					$("#user-detailform").contents().find(".table-trs").hover(function(){
						$("#user-detailform").contents().find(this).find(".table-oprate").show();
					},function(){
						$("#user-detailform").contents().find(".table-oprate").hide();
					});
					
					
					$("#user-detailform").contents().find(".table-delete").unbind("click");
					$("#user-detailform").contents().find(".table-delete").click(function(){
						var userkey = $("#user-detailform").contents().find(this).attr("userkey");
						deleteBox("确定要删除吗？",function(){
							deleteUser(userkey,code,currentpage);
						});
					});
					
				}else{
					content += "<div class=\"table-trs\">" +
									"<div class=\"no-data-show\">没有查到相关结果！</div>" +
								"</div>";
					$("#user-detailform").contents().find("#user-data-show").empty();
					$("#user-detailform").contents().find("#user-data-show").append(content);
					$("#user-detailform").contents().find(".save-btns").hide();
				}
			}else{
				content += "<div class=\"table-trs\">" +
								"<div class=\"no-data-show\">没有查到相关结果！</div>" +
							"</div>";
				$("#user-detailform").contents().find("#user-data-show").empty();
				$("#user-detailform").contents().find("#user-data-show").append(content);
				$("#user-detailform").contents().find(".save-btns").hide();
			}
		},null,null);	
	}
	//删除
	function deleteRole(id){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var param = {};
		param["id"] = id;
		var data = {
				cmd:"deleteRole",
				model:"license",
				userKey:userKey,
				data:param,
				remark:"",						
		};
		processBegin("正在删除中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("删除角色成功");
				initRole(currentPage,pageSize);				
			}else{
				processError("删除角色失败");
			}
		},null,null);
		
	}
	
	function updateRole(id){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
		var params = {};
		var param = {};
		params["name"] = encodeURI($("#role-detailform").contents().find("#role-name").val());
		//params["remark"] = encodeURI($("#role-detailform").contents().find("#role-remark").val());		
		params["describe"] = encodeURI($("#role-detailform").contents().find("#role-describe").text());
		params["schoolcode"] = schoolcode;
		params["id"] = id;
		for(var key in params){
			if(params[key] != ""){
				param[key] = params[key];
			}
		}
		var data = {
				cmd:"updateRole",
				model:"license",
				userKey:userKey,
				data:param,
				remark:"",						
		};
		processBegin("正在运行中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("修改角色成功");
				
			}else{
				processError("修改角色失败");
			}
		},null,null);			
	}
	function deleteUser(userkey,code,currentpage){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var param = {};
		param["code"] = code;
		param["userkey"] = userkey;
		var data = {
				cmd:"deleteRoleUser",
				model:"license",
				userKey:userKey,
				data:param,
				remark:"",						
		};
		processBegin("正在删除中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("删除用户成功");
				$("#user-detailform").contents().find("#user-data-show").empty();
				var pagesize = pageSizeMore * currentpage;
				initUser(1,pagesize,code);				
			}else{
				processError("删除用户失败");
			}
		},null,null);
		
	}
	function substr(str,len){
		if(str != undefined){
			if(str.length > len){
				str = str.substring(0,len-2)+"...";
				return str;
			}else{
				return str;
			}
		}else{
			return "";
		}
	}
	function isUndefined(param){
		if(param == undefined){
			param = "";
		}
		return param;
	}
	function pagebtns(){
		$("#role-name").unbind("keyup");
		$("#role-name").keyup(function(){
			this.value=this.value.replace(/^ +| +$/g,'');
		});
		$("#user-name").unbind("keyup");
		$("#user-name").keyup(function(){
			this.value=this.value.replace(/^ +| +$/g,'');
		});
		document.onkeydown = function(e){ 
		    var ev = document.all ? window.event : e;
		    if(ev.keyCode==13) {
		    	if($("#role-search-btn").css("display") == "block"){
		    		initRole(1,pageSize);
		    	}
		    	if($("#user-search-btn").css("display") == "block"){
		    		$("#user-detailform").contents().find("#user-data-show").empty();
		    		var pagesize = currentPageMore * pageSizeMore;
		    		initUser(1,pagesize);
		    	}
		    }
		};
		$("#role-search-btn").click(function(){
			dataCache = [];
			initRole(1,pageSize);
		});
		$("#user-search-btn").click(function(){
			$("#user-detailform").contents().find("#user-data-show").empty();
			dataCache = [];
			var pagesize = currentPageMore * pageSizeMore;
			initUser(1,pagesize);
		});
		
	}
	function checkUser(){
		if($("#role-detailform").contents().find("#role-name").val() == "" ){
			$("#role-detailform").contents().find("#role-name").html("不能为空");
			return false;        			
		}else{
			return true;
		}	
		
	}
	
	function initSmPages(){
		var rcH = $(".body-right",parent.document).height() - $(".right-title").height()-3;
		$(".right-content").height(rcH);
		
		var cdsH = $(".right-content").height() - $(".content-title").height() - 40;
		$(".content-data-show").height(cdsH);
	}
})();